package org.whuims.core.dataprocessor;

import org.whuims.entity.Term;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by cheng on 2016/11/25.
 */
public class TermExtractor {
    private List<String> lines = new ArrayList<String>();

    public TermExtractor(List<String> lines) {
        this.lines = lines;
    }

    public static void main(String[] args) {
        String filePath = "src/main/webapp/resource/txt/CN-GB/GB18708-2002.txt";
        DocLoader loader = new DocLoader(filePath);
        List<String> lines = loader.readLines();
        lines = loader.findMainBody(lines)[1];
        TermExtractor extractor = new TermExtractor(lines);
        extractor.extract();
    }

    public List<Term> extract() {
        List<Term> terms = new ArrayList<Term>();
        boolean toRecord = false;
        int number = -1;
        List<String> mainList = new ArrayList<String>();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < lines.size(); i++) {
            String line = lines.get(i).trim();
//            System.out.println(line);
            if (toRecord) {
                String patStr0 = "\\s*" + (number + 1) + ".+?";
                if (line.matches(patStr0)) {
                    toRecord = false;
                }
            }
            if (toRecord) {
                mainList.add(lines.get(i));
            }
            if (!toRecord && line.matches("\\d+.+?") && ((line.contains("术语") || line.endsWith("定义")))) {
                number = Integer.parseInt(line.trim().substring(0, 1));
                toRecord = true;
            }
        }
        String content = "";
        for (String str : mainList) {
//            System.out.println("++++  " + str);
            sb.append(str).append(" ");
            content = sb.toString().trim();
        }
        String[] array = content.split("。：");
        Pattern pat0 = Pattern.compile(number + "[\\d． \\.\\s\\*\\-_]+(.+?)\\s*([\\w\\(\\)，\\-,\\s]+)\\s+(.+?)[。：]", Pattern.DOTALL);
        for (String str : array) {
//            System.out.println(str);
            Matcher matcher = pat0.matcher(str.trim() + "。");
            while (matcher.find()) {
                Term term = new Term();
                String termCn = matcher.group(1).trim();
                String termEn = matcher.group(2).trim();
                String desc = matcher.group(3).trim();

                term.setContext("");
                term.setTermCn(termCn);
                term.setTermEn(termEn);
                term.setDescription(desc);
                terms.add(term);
            }
        }
        return terms;
    }
}
